<template>
  <div>
    <el-backtop target=".app-main"></el-backtop>
    <el-row :gutter="20" style="margin: 10px 0;">
      <el-col :span="12">
        <el-card class="box-card" :style="{backgroundColor: $store.state.user.baseColor}">
          <div slot="header" class="card-header">
            <span style="font-size: 120%;">{{$route.meta.title}}列表</span>
            <vxe-input v-model.trim.lazy="filterName" type="search" placeholder="快捷检索" @input="searchEvent"></vxe-input>
            <el-button @click="getCurrentList" :type="listAllShow?'':'primary'" size="mini">当前在队</el-button>
            <el-button @click="getListAll" :type="listAllShow?'primary':''" size="mini">历史所有</el-button>
            <el-button @click="refreshList" style="float: right; padding: 3px 0" type="text"
              :icon="!loading?'el-icon-refresh':'el-icon-loading'">刷新</el-button>
          </div>
          <div>
            <vxe-table resizable ref="XTable" show-overflow border height="530" stripe highlight-hover-row
              highlight-current-row resizable :loading="loading" :data="dataList" @sort-change="sortChange"
              :export-config="{}">
              <vxe-column field="createDate" title="报表时间" sortable></vxe-column>
              <vxe-column field="player" title="运动员" sortable></vxe-column>
              <vxe-column field="coach" title="教练员" sortable></vxe-column>
              <vxe-column field="scenario" title="场景" sortable v-if="usageId==3||usageId==4"></vxe-column>
              <vxe-column field="template" title="模板" sortable></vxe-column>
              <vxe-column field="" title="操作" width="150">
                <template #default="{ row }">
                  <el-button @click="previewEvent(row)" type="primary" circle size="small" icon="el-icon-view">
                  </el-button>
                  <el-button @click="updateCreateDateEvent(row)" type="primary" circle size="small" icon="el-icon-edit">
                  </el-button>
                  <el-button @click="deleteEvent(row)" type="primary" circle size="small" icon="el-icon-delete">
                  </el-button>
                </template>
              </vxe-column>
            </vxe-table>
            <vxe-pager :loading="loading" :current-page="page.currentPage" :page-size="page.pageSize"
              :total="page.totalResult" :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
              @page-change="handlePageChange">
            </vxe-pager>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="" :style="{backgroundColor: $store.state.user.baseColor}">
          <div slot="header" class="clearfix">
            <span style="font-size: 120%;">{{$route.meta.title}}查询</span>
          </div>
          <div class="card-body">
            <el-form ref="searchForm" :model="searchForm" :rules="rules" inline-message label-width="200px">
              <el-form-item label="日期" prop="createDate">
                <el-date-picker v-model="searchForm.createDate" type="date" placeholder="选择日期时间" align="left"
                  style="width: 70%;" :picker-options="pickerOptions">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="运动项目">
                <el-select @change="sportChange" v-model="searchForm.sportId" collapse-tags filterable clearable
                  placeholder="请选择" style="width: 70%;">
                  <el-option :label="item" :value="key" v-for="(item,key,index) in sportData" :key="index">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item v-if="usageId==1||usageId==2" label="运动小项">
                <el-select @change="sportItemChange" v-model="searchForm.sportItemId" collapse-tags filterable clearable
                  placeholder="请选择" style="width: 70%;">
                  <el-option :label="item" :value="key" v-for="(item,key,index) in sportItemData" :key="index">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="教练" prop="coachId">
                <el-select @change="coachChange" v-model="searchForm.coachId" collapse-tags filterable clearable
                  style="width: 70%;" placeholder="请选择">
                  <el-option :label="item" :value="key" v-for="(item,key,index) in coachData" :key="index">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item v-if="usageId==3||usageId==4" label="重点运动员">
                <el-select @change="importantChange" v-model="searchForm.importantId" collapse-tags filterable
                  placeholder="请选择" style="width: 70%;">
                  <el-option :label="item" :value="key" v-for="(item,key,index) in dict_important" :key="index">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="运动员" prop="playerId">
                <el-select v-model="searchForm.playerId" collapse-tags filterable clearable placeholder="请选择"
                  style="width: 70%;">
                  <el-option :label="item" :value="key" v-for="(item,key,index) in playerData" :key="index">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="测试项目" prop="templateId">
                <el-select @change="templateChange" v-model="searchForm.templateId" collapse-tags clearable filterable
                  placeholder="请选择" style="width: 70%;">
                  <el-option :label="item.name" :value="item.templateId" v-for="(item,index) in templateData"
                    :key="index">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item v-if="usageId==3||usageId==4" label="场景">
                <el-select v-model="searchForm.scenarioId" collapse-tags filterable placeholder="请选择"
                  style="width: 70%;">
                  <el-option :label="item" :value="key" v-for="(item,key,index) in dict_scenario" :key="index">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="分类" prop="packageId">
                <el-button-group style="display: flex;">
                  <el-select v-model="searchForm.packageId" multiple collapse-tags filterable clearable
                    placeholder="请选择">
                    <el-option :label="item.shortName" :value="item.packageId" v-for="(item,index) in packageData"
                      :key="index">
                    </el-option>
                  </el-select>
                  <el-button @click="packageSelectAll" type="primary">全选</el-button>
                </el-button-group>
              </el-form-item>
              <el-form-item>
                <el-button type="success" size="small" icon="el-icon-s-promotion" @click="submitEnter"
                  style="margin: 0 10px;"> 搜索</el-button>
                <vxe-button @click="tableClear" status="warning" icon="el-icon-refresh-right"> 清空</vxe-button>
              </el-form-item>
            </el-form>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-row style="margin: 20px 10px;">
      <el-col :span="24">
        <el-card class="box-card" v-loading="previewLoading" element-loading-text="拼命加载中" :style="{backgroundColor: $store.state.user.baseColor}">
          <div slot="header" class="card-header">
            <span style="font-size: 120%;">表单</span>
            <el-button @click="printModal=true" type="primary" size="mini" icon="el-icon-printer"
              :disabled="!printData.data">打印</el-button>
          </div>
          <div>
            <totalPrintOne v-if="printData.data" :printData="printData" :usageId="usageId" :report="true" />
            <div v-else class="empty">
              <i class="iconfont icon-kong"></i>
              <p>暂无数据</p>
            </div>
          </div>
          <div class="card-footer">
            <div v-if="printData.data">
              <div style="width: 100%;text-align: left;">评价：</div>
              <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请填入评论"
                v-model="printData.memo">
              </el-input>
              <div style="display: flex;align-items: center;">
                <div style="width: 100px;">是否保留报表:</div>
                <div style="width: 100%;text-align: left;margin-top: 5px;">
                  <el-button @click="save" type="primary" size="mini"> 保存</el-button>
                  <el-button @click="clear" type="warning" size="mini"> 取消</el-button>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <vxe-modal v-model="printModal" title="打印预览" height="600" show-zoom resize width="800" show-footer>
      <template #default>
        <div id="myPrint">
          <totalPrintOne :printData="printData" :usageId="usageId" :analysisReport="true" />
        </div>
      </template>
      <template #footer>
        <el-button @click="printEvent" type="primary" icon="el-icon-printer" size="mini">打印</el-button>
      </template>
    </vxe-modal>

    <vxe-modal v-model="updateCreateDateModal" title="选择日期" height="220" resize width="400" show-footer>
      <template #default>
        <div id="updateCreateDate">
          <el-date-picker v-model="newCreateDate" type="date" placeholder="选择日期" align="left" style="width: 70%;"
            :picker-options="pickerOptions">
          </el-date-picker>
          <p>当前仅支持修改日期</p>
        </div>
      </template>
      <template #footer>
        <el-button @click="cancelUpdateCreateDate" type="warning" icon="el-icon-close" size="mini">取消</el-button>
        <el-button @click="confirmUpdateCreateDate" type="primary" icon="el-icon-check" size="mini"
          :loading="updateCreateDateLoading">确定</el-button>
      </template>
    </vxe-modal>
  </div>
</template>

<script>
  import {
    pcm4coach,
    currentRolePlayer,
    sport_by_org,
    coach_by_org,
    pcm4player,
    meta_cache,
    coach_by_sport,
    meta_sport_item_cache,
    get_player
  } from '@/api/dict.js'
  import {
    meta_scenario,
    dailyReportDefault,
    template_allByUsageId,
    template_key,
    generate_daily_report,
    template_package,
    saveReportData,
    deleteMetaData,
    updateCreateDate,
  } from '@/api/meta.js'
  import totalPrintOne from '@/components/print/totalPrintOne.vue'
  export default {
    components: {
      totalPrintOne,
    },
    data() {
      return {
        pickerOptions: {
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          }, {
            text: '昨天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', date);
            }
          }, {
            text: '一周前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date);
            }
          }, {
            text: '一月前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', date);
            }
          }, {
            text: '半年前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 30 * 6);
              picker.$emit('pick', date);
            }
          }, {
            text: '一年前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 30 * 12);
              picker.$emit('pick', date);
            }
          }, ]
        },
        usageId: this.$route.meta.usageId,
        dict_usage: this.$store.state.user.dict_usage,
        invalidateCache: false,
        page: {
          currentPage: 1,
          pageSize: 10,
          totalResult: 0
        },
        defaultDataList: [],
        dataList: [],
        loading: false,
        filterName: '',
        searchProps: [],
        dict_player: {},
        dict_sport: {},
        dict_coach: {},
        dict_meta: {},
        dict_scenario: {},
        sportData: {},
        sportItemData: {},
        coachData: {},
        templateData: [],
        packageData: [],
        playerData: {},
        dict_important: {
          1: '重点',
          2: '非重点',
          3: '全部'
        },
        searchForm: {
          createDate: '',
          templateId: '',
          coachId: '',
          playerId: '',
          sportId: '',
          sportItemId: '',
          scenarioId: '',
          importantId: '3',
          packageId: '',
        },
        rules: {
          createDate: [{
            required: true,
            message: '这是必选项',
            trigger: 'change'
          }, ],
          templateId: [{
            required: true,
            message: '这是必选项',
            trigger: 'change'
          }, ],
          playerId: [{
            required: true,
            message: '这是必选项',
            trigger: 'change'
          }, ],
          packageId: [{
            required: false,
            message: '这是必选项',
            trigger: 'change'
          }, ],
        },
        printData: {},
        previewLoading: false,
        printModal: false,
        updateCreateDateModal: false,
        search: false,
        newCreateDate: "",
        currentRow: {},
        updateCreateDateLoading: false,
        dict_template: {},
        listAllShow: true,
        currentData: {}
      }
    },
    created() {
      this.init_dict().then(() => {
        this.dailyReportDefault()
      })
    },
    watch: {
      filterName(val) {
        if (!val) {
          this.page = {
            currentPage: 1,
            pageSize: 10,
            totalResult: 0,
          }
          this.search = false
          this.findList()
        }
      }
    },
    methods: {
      // 当前在队
      getCurrentList() {
        this.listAllShow = false
        this.dailyReportDefault(false)
      },
      // 历史所有
      getListAll() {
        this.listAllShow = true
        this.dailyReportDefault(true)
      },
      printEvent() {
        const divEl = document.getElementById('myPrint')
        document.title = this.printData.player + this.printData.date + this.$route.meta.title
        this.$XPrint({
          sheetName: '',
          content: divEl.innerHTML
        })
      },
      clear() {
        let data = {
          createDate: this.currentData.createDate + ' 00:00:00',
          openDate: '1970-01-01 00:00:00',
          closeDate: '1970-01-01 00:00:00',
          packageIds: this.currentData.packageIds,
          usageId: this.usageId,
          metaIds: this.currentData.metaIds,
          scenarioId: this.currentData.scenarioId,
          playerIds: this.currentData.playerId,
          reportTypeItem: 1,
          memo: '',
          reportJson: JSON.stringify(this.printData)
        }
        saveReportData(data).then(res => {
          if (res.code === 200) {
            this.printData.memo = ''
            this.$message.success('取消成功！')
          } else {
            this.$message.error(res.message)
          }
        })
      },
      save() {
        let data = {
          createDate: this.currentData.createDate + ' 00:00:00',
          openDate: '1970-01-01 00:00:00',
          closeDate: '1970-01-01 00:00:00',
          packageIds: this.currentData.packageIds,
          usageId: this.usageId,
          metaIds: this.currentData.metaIds,
          scenarioId: this.currentData.scenarioId,
          playerIds: this.currentData.playerId,
          reportTypeItem: 1,
          memo: this.printData.memo,
          reportJson: JSON.stringify(this.printData)
        }
        saveReportData(data).then(res => {
          if (res.code === 200) {
            this.$message.success('保存成功！')
          } else {
            this.$message.error(res.message)
          }
        })
      },
      submitEnter() {
        this.rules.packageId[0].required = true
        this.$refs.searchForm.validate((valid) => {
          if (valid) {
            let data = {
              playerID: this.searchForm.playerId,
              usageID: this.usageId,
              templateID: this.searchForm.templateId,
              createDate: this.$moment(this.searchForm.createDate).format('YYYY-MM-DD') + ' 00:00:00',
              startTime: '1970-01-01 00:00:00',
              endTime: '1970-01-01 00:00:00',
              packageIDs: this.searchForm.packageId.join(','),
              metaIDs: 0,
            }
            if (this.searchForm.scenarioId) {
              data.scenarioID = this.searchForm.scenarioId
            }
            this.getReport(data)
          } else {
            return false
          }
        })
      },
      previewEvent(row) {
        this.currentData = row
        let data = {
          playerID: row.playerId,
          usageID: this.usageId,
          scenarioID: row.scenarioId,
          templateID: row.templateId,
          createDate: row.createDate + ' 00:00:00',
          startTime: '1970-01-01 00:00:00',
          endTime: '1970-01-01 00:00:00',
          packageIDs: row.packageIds,
          metaIDs: row.metaIds,
        }
        this.getReport(data)
      },
      getReport(data) {
        this.previewLoading = true
        generate_daily_report(data).then(res => {
          if (res.code === 200) {
            if (res.data.data.length != 0) {
              this.printData = res.data
              this.printData.scenario = this.dict_scenario[data.scenarioID]
              this.$nextTick(() => {
                let appMain = document.getElementsByClassName('app-main')
                appMain[0].scrollTop = 700
              })
            } else {
              this.$message.warning('未找到与条件匹配的任何数据')
              this.printData = {}
            }
          } else {
            this.$message.warning('未找到与条件匹配的任何数据')
            this.printData = {}
          }
          this.previewLoading = false
        })
      },
      updateCreateDateEvent(row) {
        this.currentRow = row;
        this.updateCreateDateModal = true;
      },
      cancelUpdateCreateDate() {
        this.updateCreateDateModal = false;
      },
      confirmUpdateCreateDate() {
        this.updateCreateDateLoading = true;
        let data = {
          playerId: this.currentRow.playerId,
          usageId: this.usageId,
          scenarioId: this.currentRow.scenarioId,
          templateId: this.currentRow.templateId,
          createDate: this.currentRow.createDate + ' 00:00:00',
        }
        data.newCreateDate = this.$moment(this.newCreateDate).format("YYYY-MM-DD") + " 00:00:00";
        updateCreateDate(data).then((res) => {
          if (res.code == 200) {
            data.createDate = this.$moment(this.newCreateDate).format("YYYY-MM-DD")
            Object.assign(this.currentRow, data)
            this.updateCreateDateModal = false;
            this.updateCreateDateLoading = false;
            this.$message.success('修改成功')
          }
        })
      },
      deleteEvent(row) {
        this.$confirm('此操作将永久删除该条记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let data = {
            playerId: row.playerId,
            usageId: this.usageId,
            scenarioId: row.scenarioId,
            templateId: row.templateId,
            createDate: row.createDate + ' 00:00:00',
          }
          deleteMetaData(data).then((res) => {
            if (res.code == 200) {
              this.refreshList();
              this.$message.success('删除成功')
            } else {
              this.$message({
                type: 'info',
                message: '删除失败' + res.message
              });
            }

          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      tableClear() {
        this.searchForm.templateId = ''
        this.searchForm.createDate = ''
        this.searchForm.playerId = ''
      },
      packageSelectAll() {
        this.searchForm.packageId = []
        this.packageData.forEach(item => {
          this.searchForm.packageId.push(item.packageId)
        })
      },
      sportChange(val) {
        this.coachData = {}
        this.searchForm.coachId = ''
        this.playerData = {}
        this.searchForm.playerId = ''
        this.sportItemData = {}
        this.searchForm.sportItemId = ''
        meta_sport_item_cache({
          sportId: val || this.searchForm.sportId
        }).then(res => {
          this.sportItemData = res
        })
        coach_by_sport({
          sportId: val || this.searchForm.sportId
        }).then(res => {
          this.coachData = res
        })
        if (this.usageId == 3 || this.usageId == 4) {
          let data = {
            usageId: this.usageId,
            sportId: val || this.searchForm.sportId,
            isImportant: this.searchForm.importantId,
          }
          this.getPlayer(data)
        }
      },
      importantChange(val) {
        let data = {
          usageId: this.usageId,
          isImportant: val || this.searchForm.importantId,
        }
        this.getPlayer(data)
      },
      getPlayer(data) {
        this.playerData = {}
        this.searchForm.playerId = ''
        get_player(data).then(res => {
          this.playerData = res
        })
      },
      sportItemChange(val) {
        this.coachData = {}
        this.searchForm.coachId = ''
        coach_by_sport({
          sportId: this.searchForm.sportId,
          sportItemId: this.searchForm.sportItemId
        }).then(res => {
          this.coachData = res
        })
      },
      templateChange(val) {
        this.packageData = []
        this.searchForm.packageId = ''
        template_package(val).then(res => {
          this.packageData = res.data
        })
      },
      coachChange(val) {
        this.playerData = {}
        this.searchForm.playerId = ''
        if (this.usageId == 3 || this.usageId == 4) {
          let data = {
            usageId: this.usageId,
            coachId: val || this.searchForm.coachId,
            isImportant: this.searchForm.importantId,
          }
          if (this.searchForm.sportId) data.sportId = this.searchForm.sportId
          this.getPlayer(data)
        } else {
          pcm4player({
            coachId: this.searchForm.coachId || val
          }).then(res => {
            this.playerData = res
          })
        }
      },
      refreshList() {
        this.invalidateCache = true
        this.dailyReportDefault()
      },
      dailyReportDefault(all) {
        let data = {
          usageId: this.usageId,
          type: 'search',
          invalidateCache: this.invalidateCache
        }
        data.all = this.listAllShow
        this.loading = true
        dailyReportDefault(data).then(res => {
          if (res.code === 200) {
            if (res.data.length != 0) {
              this.init_list_data(res.data)
            } else {
              this.defaultDataList = []
            }
          } else {
            this.defaultDataList = []
            this.$message.error(res.message)
          }
        }).then(() => {
          this.findList()
        })
      },
      init_list_data(data) {
        data.forEach(item => {
          item.player = this.dict_player[item.playerId]
          item.coach = this.dict_coach[item.coachId]
          item.scenario = this.dict_scenario[item.scenarioId]
          item.template = this.dict_template[item.templateId]
        })
        this.searchProps = Object.keys(data[0])
        this.defaultDataList = data
      },
      init_dict() {
        return new Promise((resolve, reject) => {
          this.loading = true
          sport_by_org().then(res => {
            this.dict_sport = res
            this.sportData = res
          })
          coach_by_org().then(res => {
            this.dict_coach = res
            this.coachData = res
          })
          template_allByUsageId({
            usageId: this.usageId
          }).then(res => {
            res.data.forEach(item => {
              this.dict_template[item.templateId] = item.name
            })
            this.templateData = res.data
          })
          meta_cache().then(res => {
            this.dict_meta = res
          })
          meta_scenario().then(res => {
            res.data.forEach(item => {
              this.dict_scenario[item.scenarioId] = item.name
            })
            if (this.usageId == 4) {
              this.dict_scenario = {
                '6': '晨空腹'
              }
              this.searchForm.scenarioId = '6'
            }
          })
          currentRolePlayer().then(res => {
            this.dict_player = res
            resolve()
          })
        })
      },
      searchEvent() {
        const filterName = this.$XEUtils.toValueString(this.filterName).trim().toLowerCase()
        if (filterName) {
          const filterRE = filterName
          const searchProps = this.searchProps
          const rest = this.defaultDataList.filter(item => searchProps.some(key => this.$XEUtils.toValueString(item[
            key]).toLowerCase().indexOf(filterName) > -1))
          this.dataList = rest.map(row => {
            const item = Object.assign({}, row)
            searchProps.forEach(key => {
              item[key] = this.$XEUtils.toValueString(item[key]).replace(filterRE, match => match)
            })
            return item
          })
          this.page = {
            currentPage: 1,
            pageSize: this.dataList.length,
            totalResult: this.dataList.length
          }
          this.search = true
        } else {
          this.dataList = this.defaultDataList
        }
      },
      handlePageChange({
        currentPage,
        pageSize
      }) {
        this.page.currentPage = currentPage
        this.page.pageSize = pageSize
        this.findList()
      },
      sortChange() {
        if (!this.search) {
          this.page.currentPage = 1
          this.page.pageSize = this.defaultDataList.length
          this.findList()
        } else {
          this.page.pageSize = this.dataList.length
        }
      },
      findList() {
        this.loading = true
        setTimeout(() => {
          if (this.insertSuccess) {
            this.page.totalResult = this.defaultDataList.length
            this.page.currentPage = Math.ceil(this.page.totalResult / this.page.pageSize)
            this.dataList = this.defaultDataList.slice((this.page.currentPage - 1) * this.page
              .pageSize, this.page.currentPage * this.page.pageSize)
            this.$refs.XTable.setCurrentRow(this.dataList[this.dataList.length - 1])
            this.insertSuccess = false
          } else {
            this.page.totalResult = this.defaultDataList.length
            this.dataList = this.defaultDataList.slice((this.page.currentPage - 1) * this.page
              .pageSize, this.page.currentPage * this.page.pageSize)
          }
          this.loading = false
        }, 300)
      },
    }
  }
</script>

<style lang="scss" scoped>
  .card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .card-body {
    height: 590px;
  }

  .card-footer {
    width: 100%;
    text-align: center;
    margin-top: 20px;
  }

  .empty {
    width: 100%;
    text-align: center;
    color: #cbcbcb;

    i {
      font-size: 400%;
    }
  }
</style>
